package com.cqupt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.service.ActionService;
import com.cqupt.utils.APIUtils;
import com.cqupt.utils.ActionUtils;
import com.cqupt.utils.TextUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动作接口实现类
 **/
@Service
public class ActionServiceImpl implements ActionService {
    // 适用于linux操作系统
    private final String[] commands = {
            "shutdown -h now",  //关机
            "shutdown -r now",  //重启
    };

    /**
     * @see ActionService#sendCommandToHost(int, String, String, String)
     */
    @Override
    public Map<String, Object> sendCommandToHost(int code, String hostId, String user, String password) {
        final String token = APIUtils.getToken();
        String ip = getIpByHostId(token, hostId);

        String out = ActionUtils.sendCommandToHost(ip, user, password, commands[code]);

        Map<String, Object> resMap = new HashMap<String, Object>() {{
            put("result", out);
        }};

        return resMap;
    }

    // 向windows操作系统的主机发送命令，仅支持关闭操作
    // return:true/false
    @Override
    public Map<String, Object> sendCommandToWindow(String hostid, String user, String password) {
        String token = APIUtils.getToken();
        // 获取目标主机ip
        String ip = getIpByHostId(token, hostid);
        String result = null;
        // 执行关机命令
        if(ActionUtils.controlWindowHost(ip,user,password)){
            result = "success";
        } else {
            result = "fail";
        }
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("result", result);
        return resMap;
    }

    /**
     * 通过hostId获取主机IP
     *
     * @param token
     * @param hostId
     * @return String主机IP
     */
    public String getIpByHostId(String token, String hostId) {
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 2);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("hostids", hostId);
                put("output", new String[]{"host"});
                put("selectInterfaces", new String[]{"ip"});
            }});
        }};

        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
        String resStr = (String) TextUtils.getInnerValue(resultList.get(0), "interfaces", "ip");

        return resStr;
    }
}
